Components.utils.import("resource://lucidity/lucidapi.jsm");
Components.utils.import("resource://gre/modules/JSON.jsm");

var inopts = null;

function getPublicKeyBox()
{
    return document.getElementById('pubkeylist');
}

function getEncryptionKeyBox()
{
    return document.getElementById('enckeylist');
}

function onSelect()
{
    var pubBox = getPublicKeyBox().getTree().view;
    var encBox = getEncryptionKeyBox().getTree().view;
    if (pubBox && pubBox.selection.currentIndex > -1)
    {
        document.getElementById("pubkey-add-button").disabled = false;
    }
    else
    {
        document.getElementById("pubkey-add-button").disabled = true;
    }
    if (encBox && encBox.selection.currentIndex > -1)
    {
        document.getElementById("enckey-remove-button").disabled = false;
    }
    else
    {
        document.getElementById("enckey-remove-button").disabled = true;
    }
}

function onAddEncryptionKey()
{
    try {
        var encBox = getEncryptionKeyBox();
        var pubBox = getPublicKeyBox();
        pubBox.moveSelectedRows(encBox);
    } catch (e) {
        Components.utils.reportError(e);
        if (e.stack)
            Components.utils.reportError(e.stack);
    }
}

function onRemoveEncryptionKey()
{
    try {
        var encBox = getEncryptionKeyBox();
        var pubBox = getPublicKeyBox();
        encBox.moveSelectedRows(pubBox);
    } catch (e) {
        Components.utils.reportError(e);
        if (e.stack)
            Components.utils.reportError(e.stack);
    }
}

function onAccept( win )
{
    if (win.arguments == undefined)
        return true;

    var outopts = {
        filename: inopts.filename
    };

    var defkeymenulist = document.getElementById("defkey-menulist");
    var sigKeyIds = defkeymenulist.value;

    var encBox = getEncryptionKeyBox();
    var pubKeys = [];
    encBox.getFullRowData().forEach(function(rowdata){
        pubKeys.push(rowdata["keyid"]);
    });

    outopts.encKeyIds = pubKeys.length > 0 ? pubKeys.join(" ") : "";

    var signingMode = document.getElementById("signingmode-radiogroup").value
    if (signingMode > 0)
    {
        outopts.sigKeyIds = sigKeyIds;
        outopts.clearsign = (signingMode == 2);
    }

    outopts.format = document.getElementById("textmodeCheckbox").checked ? 't' : 'b';

    lucidapi.assert(typeof(outopts.encKeyIds) == "string");
    if (outopts.encKeyIds.length < 1 && (!outopts.sigKeyIds))
    {
        lucidapi.promptAlert("mustchoosesecorpubkey",[]);
        return false;
    }

    outopts.accepted = true;

    var str      = Components.classes["@mozilla.org/supports-string;1"].
                              createInstance(Components.interfaces.nsISupportsString);
    str.data     = JSON.toString(outopts);

    if (!(win.arguments[1] instanceof Components.interfaces.nsIMutableArray))
        lucidapi.error("bad juju");

    win.arguments[1].appendElement(str,false);
    return true;
}

function updateDisabledWidgets()
{
    var signingmoderadiogroup = document.getElementById("signingmode-radiogroup");
    var menlist = document.getElementById("defkey-menulist");
    if (menlist.value == "")
    {
        signingmoderadiogroup.disabled = true;
    }
    else
    {
        signingmoderadiogroup.disabled = false;
    }
    if (signingmoderadiogroup.value == 2 && menlist.value != "")
    {
        document.getElementById("encKeylistDeck").selectedIndex = 1;
    }
    else
    {
        document.getElementById("encKeylistDeck").selectedIndex = 0;
    }

    return true;
}

function toggleAddressbook( button )
{
    var box = document.getElementById("addressbox");
    if (box.hidden == true)
    {
        box.hidden = false;
        button.label = lucidapi.i18n.getString("addressbook.close");
    }
    else
    {
        box.hidden = true;
        button.label = lucidapi.i18n.getString("addressbook.open");
    }
    sizeToContent();
}

function onLoad( win )
{
    try {
//    if (win.arguments == undefined)
//        return;

    inopts = JSON.fromString(win.arguments[0]);

    var preselect = inopts.preselect;
    preselect = preselect.split(" ");

    var preselectmap = {};
    var ii = 0;
    for (ii = 0; ii < preselect.length; ii++)
    {
        if (preselect[ii].indexOf("@") > 0)
        {
            preselectmap[preselect[ii]] = true;
        }
    }

    var encBox = getEncryptionKeyBox();
//    encBox.invertedToggle = true;

    var pubBox = getPublicKeyBox();
    updateGenericBox(pubBox,false);

    updateKeyMenulist(document.getElementById("defkey-menulist"),inopts.presig);
    var tmpDat = pubBox.getFullRowData();
    tmpDat.forEach(function(rowdata) {
        for (var email in preselectmap)
        {
            if (rowdata["userid"].indexOf(email) > -1)
            {
                pubBox.moveSelectedRows(encBox,rowdata);
                preselectmap[email] = false;
            }
        }
    });

    var suggestclearsign = false;
    for (email in preselectmap)
    {
        if (preselectmap[email])
            suggestclearsign = true;
    }

    var sigmoderadiogroup = document.getElementById("signingmode-radiogroup");
    sigmoderadiogroup.value = suggestclearsign ? "2" : lucidapi.config.default_signing_mode;

    onSelect();

    document.getElementById("textmodeCheckbox").checked = lucidapi.config.default_textmode_encrypt && (!inopts.forcebin);
    var defkeymenulist = document.getElementById("defkey-menulist");
    defkeymenulist.addEventListener( "command", updateDisabledWidgets, false);
    sigmoderadiogroup.addEventListener( "command", updateDisabledWidgets, false);
    updateDisabledWidgets();
    } catch (e) {
        lucidapi.error(e);
    }
}

